package com.cyys.modules.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.cyys.common.utils.date.DateUtil;
import com.cyys.modules.core.jwt.JwtUtils;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Created by ThinkPad on 2017/6/20.
 */
public class HeaderTokenInterceptor implements HandlerInterceptor {

	private final static Logger logger = LoggerFactory.getLogger(HeaderTokenInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
			throws Exception {
		String requestURI = request.getRequestURI();
		String tokenStr = request.getParameter("token");
		String token = "";
//		if (!requestURI.contains("/token/")) {
			token = request.getHeader("token");
			if (token == null && tokenStr == null) {
				String str = "{'success':false,'errorCode':'11','msg':'缺少token，无法验证','data':null}";
				dealErrorReturn(request, response, JSONObject.parseObject(str));
				return false;
			}
			if (tokenStr != null) {
				token = tokenStr;
			}
			Claims claims = null;
			try{
				claims = JwtUtils.parseJWT(token);
			}catch(Exception ex){
				String str = "{'success':false,'errorCode':'13','msg':'token验证失败','data':null}";
				dealErrorReturn(request, response, JSONObject.parseObject(str));
				return false;
			}
			if(DateUtil.getIntervalHours(claims.getExpiration(), new Date ()) >= 24){
				String str = "{'success':false,'errorCode':'12','msg':'token過期','data':null}";
				dealErrorReturn(request, response, JSONObject.parseObject(str));
				return false;
			}
//		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object o, Exception e) throws Exception {
	}

	// 检测到没有token，直接返回不验证
	public void dealErrorReturn(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object obj) {
		PrintWriter writer = null;
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setContentType("text/html; charset=utf-8");
		try {
			writer = httpServletResponse.getWriter();
			writer.print(obj);
		} catch (IOException ex) {
			logger.error("response error", ex);
		} finally {
			if (writer != null)
				writer.close();
		}
	}

}